<template>
  <div class="groups-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1>分组管理</h1>
        <p>管理学生分组，组织考试安排</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <i class="fas fa-plus"></i>
          创建分组
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索分组名称..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
          <el-option label="全部" value="" />
          <el-option label="活跃" value="active" />
          <el-option label="已归档" value="archived" />
        </el-select>
      </div>
      <div class="search-right">
        <el-button :icon="Refresh" @click="loadGroups">刷新</el-button>
      </div>
    </div>
    
    <!-- 分组列表 -->
    <div class="groups-grid">
      <div 
        v-for="group in filteredGroups" 
        :key="group.id" 
        class="group-card"
        :class="{ archived: group.status === 'archived' }"
      >
        <div class="group-header">
          <div class="group-info">
            <h3>{{ group.name }}</h3>
            <el-tag 
              :type="group.status === 'active' ? 'success' : 'info'"
              size="small"
            >
              {{ group.status === 'active' ? '活跃' : '已归档' }}
            </el-tag>
          </div>
          <el-dropdown @command="(command) => handleGroupAction(command, group)">
            <el-button circle :icon="MoreFilled" size="small" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">
                  <i class="fas fa-edit"></i>
                  编辑
                </el-dropdown-item>
                <el-dropdown-item divided command="archive" v-if="group.status === 'active'">
                  <i class="fas fa-archive"></i>
                  归档
                </el-dropdown-item>
                <el-dropdown-item command="activate" v-else>
                  <i class="fas fa-undo"></i>
                  激活
                </el-dropdown-item>
                <el-dropdown-item command="delete" style="color: #f56c6c">
                  <i class="fas fa-trash"></i>
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <div class="group-description">
          <p>{{ group.description || '暂无描述' }}</p>
        </div>
        
        <div class="group-stats">
          <div class="stat-item">
            <i class="fas fa-users"></i>
            <span>{{ group.studentCount }} 名学生</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-file-alt"></i>
            <span>{{ group.examCount }} 场考试</span>
          </div>
          <div class="stat-item">
            <i class="fas fa-calendar"></i>
            <span>{{ formatDate(group.createdAt) }}</span>
          </div>
        </div>
        
        <div class="group-actions">
          <el-button 
            size="small" 
            @click="viewGroupDetails(group)"
          >
            查看详情
          </el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="manageStudents(group)"
          >
            管理学生
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="filteredGroups.length === 0" class="empty-state">
      <i class="fas fa-users"></i>
      <h3>暂无分组</h3>
      <p>创建第一个学生分组来开始组织您的考试</p>
      <el-button type="primary" @click="showCreateDialog = true">
        创建分组
      </el-button>
    </div>
    
    <!-- 创建/编辑分组对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingGroup ? '编辑分组' : '创建分组'"
      width="500px"
    >
      <el-form
        ref="groupFormRef"
        :model="groupForm"
        :rules="groupFormRules"
        label-width="80px"
      >
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="分组描述" prop="description">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分组描述（可选）"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="groupForm.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="archived">已归档</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveGroup" :loading="saving">
          {{ editingGroup ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 学生管理对话框 -->
    <el-dialog
      v-model="showStudentsDialog"
      title="管理学生"
      width="800px"
    >
      <div class="students-management">
        <div class="students-header">
          <el-input
            v-model="studentSearchKeyword"
            placeholder="搜索学生..."
            :prefix-icon="Search"
            style="width: 300px"
          />
          <el-button type="primary" @click="showAddStudentDialog = true">
            添加学生
          </el-button>
        </div>
        
        <el-table :data="currentGroupStudents" style="width: 100%">
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="studentId" label="学号" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="joinedAt" label="加入时间">
            <template #default="{ row }">
              {{ formatDate(row.joinedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button
                size="small"
                type="danger"
                link
                @click="removeStudentFromGroup(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    
    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="showAddStudentDialog"
      title="添加学生到分组"
      width="500px"
    >
      <div class="add-students">
        <el-form @submit.prevent="searchUserByUsername">
          <el-form-item label="用户名">
            <el-input
              v-model="searchUsername"
              placeholder="请输入要添加的学生用户名"
              :prefix-icon="Search"
              @keyup.enter="searchUserByUsername"
            >
              <template #append>
                <el-button @click="searchUserByUsername" :loading="searchingUser">
                  搜索
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        
        <!-- 搜索结果 -->
        <div v-if="foundUser" class="search-result">
          <div class="user-card">
            <div class="user-info">
              <h4>{{ foundUser.realName || foundUser.username }}</h4>
              <p>用户名: {{ foundUser.username }}</p>
              <p v-if="foundUser.email">邮箱: {{ foundUser.email }}</p>
            </div>
            <el-button 
              type="primary" 
              size="small"
              @click="addFoundUserToGroup"
              :disabled="isUserInGroup(foundUser)"
            >
              {{ isUserInGroup(foundUser) ? '已在分组中' : '添加到分组' }}
            </el-button>
          </div>
        </div>
        
        <div v-if="searchError" class="search-error">
          <el-alert
            :title="searchError"
            type="warning"
            :closable="false"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="closeAddStudentDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, MoreFilled } from '@element-plus/icons-vue'
import { 
  getGroupList, 
  createGroup, 
  updateGroup, 
  deleteGroup
} from '@/api/rbac/admin'
import { getUserByUsername } from '@/api/rbac/rbac'
import { addUsersToGroup, removeUsersFromGroup } from '@/api/rbac/userGroups'
import { useAppStore } from '@/stores'

const searchKeyword = ref('')
const statusFilter = ref('')
const showCreateDialog = ref(false)
const showStudentsDialog = ref(false)
const showAddStudentDialog = ref(false)
const saving = ref(false)
const editingGroup = ref(null)
const currentGroup = ref(null)
const studentSearchKeyword = ref('')
const searchUsername = ref('')
const foundUser = ref(null)
const searchError = ref('')
const searchingUser = ref(false)

const groupFormRef = ref()

const groups = ref([])

const currentGroupStudents = ref([])

const groupForm = ref({
  name: '',
  description: '',
  status: 'active'
})

const groupFormRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分组名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const filteredGroups = computed(() => {
  let result = groups.value
  
  if (searchKeyword.value) {
    result = result.filter(group => 
      group.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (group.description && group.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(group => group.status === statusFilter.value)
  }
  
  return result
})

const appStore = useAppStore()

const loadGroups = async () => {
  try {
    appStore.setLoading(true)
    const response = await getGroupList()
    
    if (response.data && response.code === 200) {
      // 将后端数据格式转换为前端需要的格式
      groups.value = response.data.map(group => ({
        id: group.groupId,
        name: group.groupName,
        description: '', // 后端暂无描述字段
        status: 'active', // 默认为活跃状态
        studentCount: group.members ? group.members.length : 0,
        examCount: 0, // 暂时设为0，需要后端支持
        createdAt: group.createdAt ? group.createdAt.split('T')[0] : '',
        members: group.members || []
      }))
    }
  } catch (error) {
    console.error('加载分组列表失败:', error)
    ElMessage.error('加载分组列表失败')
  } finally {
    appStore.setLoading(false)
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleGroupAction = async (command, group) => {
  switch (command) {
    case 'edit':
      editGroup(group)
      break
    case 'archive':
      await toggleGroupStatus(group, 'archived')
      break
    case 'activate':
      await toggleGroupStatus(group, 'active')
      break
    case 'delete':
      await deleteGroupConfirm(group)
      break
  }
}

const editGroup = (group) => {
  editingGroup.value = group
  groupForm.value = {
    name: group.name,
    description: group.description || '',
    status: group.status
  }
  showCreateDialog.value = true
}

const manageStudents = async (group) => {
  currentGroup.value = group
  showStudentsDialog.value = true
  await loadGroupStudents(group.id)
}

const loadGroupStudents = async (groupId) => {
  try {
    // 从已加载的分组数据中获取成员信息
    const group = groups.value.find(g => g.id === groupId)
    if (group && group.members) {
      currentGroupStudents.value = group.members.map(member => ({
        id: member.userId,
        name: member.realName || member.username, // 优先使用realName，fallback到username
        studentId: member.username, // 使用username作为学号
        email: member.email,
        joinedAt: group.createdAt // 使用分组创建时间作为加入时间
      }))
    } else {
      currentGroupStudents.value = []
    }
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  }
}

const searchUserByUsername = async () => {
  if (!searchUsername.value.trim()) {
    searchError.value = '请输入用户名'
    return
  }
  
  try {
    searchingUser.value = true
    searchError.value = ''
    foundUser.value = null
    
    const response = await getUserByUsername(searchUsername.value.trim())
    console.log('搜索用户响应:', response)
    
    if (response.code === 200 && response.data) {
      foundUser.value = response.data
    } else {
      searchError.value = response.message || '未找到该用户'
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    searchError.value = '搜索失败，请检查用户名是否正确'
  } finally {
    searchingUser.value = false
  }
}

const isUserInGroup = (user) => {
  return currentGroupStudents.value.some(student => student.id === user.userId)
}

const addFoundUserToGroup = async () => {
  if (!foundUser.value || !currentGroup.value) return
  
  try {
    const response = await addUsersToGroup({
      groupId: currentGroup.value.id,
      userIds: [foundUser.value.userId]
    })
    
    console.log('添加用户到分组响应:', response)
    
    if (response.code === 200 || response.code === 0) {
      // 添加到本地列表
      const newStudent = {
        id: foundUser.value.userId,
        name: foundUser.value.realName || foundUser.value.username,
        studentId: foundUser.value.username,
        email: foundUser.value.email,
        joinedAt: new Date().toISOString().split('T')[0]
      }
      
      currentGroupStudents.value.push(newStudent)
      
      // 更新分组的学生数量
      if (currentGroup.value) {
        currentGroup.value.studentCount = currentGroupStudents.value.length
        
        // 同时更新groups列表中对应分组的数据
        const groupIndex = groups.value.findIndex(g => g.id === currentGroup.value.id)
        if (groupIndex !== -1) {
          groups.value[groupIndex].studentCount = currentGroupStudents.value.length
          if (!groups.value[groupIndex].members) {
            groups.value[groupIndex].members = []
          }
          groups.value[groupIndex].members.push({
            userId: foundUser.value.userId,
            username: foundUser.value.username,
            realName: foundUser.value.realName,
            email: foundUser.value.email
          })
        }
      }
      
      ElMessage.success(`成功将 ${foundUser.value.realName || foundUser.value.username} 添加到分组`)
      
      // 清空搜索结果
      foundUser.value = null
      searchUsername.value = ''
    } else {
      ElMessage.error(response.message || '添加学生失败')
    }
  } catch (error) {
    console.error('添加学生失败:', error)
    ElMessage.error('添加学生失败')
  }
}

const closeAddStudentDialog = () => {
  showAddStudentDialog.value = false
  foundUser.value = null
  searchUsername.value = ''
  searchError.value = ''
}

const toggleGroupStatus = async (group, status) => {
  try {
    const response = await updateGroup(group.id, { status })
    if (response.code === 0) {
      group.status = status
      ElMessage.success(`分组已${status === 'active' ? '激活' : '归档'}`)
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('切换分组状态失败:', error)
    ElMessage.error('操作失败')
  }
}

const deleteGroupConfirm = async (group) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分组"${group.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteGroup(group.id)
    groups.value = groups.value.filter(g => g.id !== group.id)
    ElMessage.success('分组删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSaveGroup = async () => {
  try {
    await groupFormRef.value.validate()
    saving.value = true
    
    if (editingGroup.value) {
      const response = await updateGroup(editingGroup.value.id, groupForm.value)
      if (response.data) {
        Object.assign(editingGroup.value, response.data)
        ElMessage.success('分组更新成功')
      }
    } else {
      const response = await createGroup(groupForm.value)
      if (response.data) {
        groups.value.unshift({
          ...response.data,
          studentCount: 0,
          examCount: 0,
          createdAt: new Date().toISOString().split('T')[0]
        })
        ElMessage.success('分组创建成功')
      }
    }
    
    showCreateDialog.value = false
    resetGroupForm()
  } catch (error) {
    ElMessage.error(editingGroup.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

const resetGroupForm = () => {
  groupForm.value = {
    name: '',
    description: '',
    status: 'active'
  }
  editingGroup.value = null
  groupFormRef.value?.resetFields()
}

const viewGroupDetails = (group) => {
  // 跳转到分组详情页面
}



const removeStudentFromGroup = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要将"${student.name}"从分组中移除吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await removeUsersFromGroup({
      groupId: currentGroup.value.id,
      userIds: [student.id]
    })
    
    console.log('移除用户响应:', response)
    
    if (response.code === 200 || response.code === 0) {
      currentGroupStudents.value = currentGroupStudents.value.filter(
        s => s.id !== student.id
      )
      
      // 更新分组的学生数量
      if (currentGroup.value) {
        currentGroup.value.studentCount = currentGroupStudents.value.length
        
        // 同时更新groups列表中对应分组的数据
        const groupIndex = groups.value.findIndex(g => g.id === currentGroup.value.id)
        if (groupIndex !== -1) {
          groups.value[groupIndex].studentCount = currentGroupStudents.value.length
          if (groups.value[groupIndex].members) {
            groups.value[groupIndex].members = groups.value[groupIndex].members.filter(
              member => member.userId !== student.id
            )
          }
        }
      }
      
      ElMessage.success(`成功将 ${student.name} 从分组中移除`)
    } else {
      ElMessage.error(response.message || '移除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除学生失败:', error)
      ElMessage.error('移除失败')
    }
  }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}



onMounted(() => {
  loadGroups()
})
</script>

<style lang="scss" scoped>
.groups-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  
  .header-left {
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
    
    p {
      color: var(--neutral-500);
      font-size: 16px;
    }
  }
}

.search-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .search-left {
    display: flex;
    gap: 16px;
    
    .el-input {
      width: 300px;
    }
    
    .el-select {
      width: 150px;
    }
  }
}

.groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.group-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }
  
  &.archived {
    opacity: 0.7;
  }
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  
  .group-info {
    flex: 1;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: var(--neutral-700);
      margin-bottom: 8px;
    }
  }
}

.group-description {
  margin-bottom: 20px;
  
  p {
    color: var(--neutral-500);
    font-size: 14px;
    line-height: 1.5;
  }
}

.group-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
  
  .stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: var(--neutral-500);
    
    i {
      width: 16px;
      color: var(--neutral-400);
    }
  }
}

.group-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  
  i {
    font-size: 64px;
    color: var(--neutral-300);
    margin-bottom: 24px;
  }
  
  h3 {
    font-size: 20px;
    color: var(--neutral-500);
    margin-bottom: 12px;
  }
  
  p {
    color: var(--neutral-400);
    margin-bottom: 24px;
  }
}

.students-management {
  .students-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
}

.add-students {
  .search-result {
    margin-top: 20px;
    
    .user-card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border: 1px solid var(--neutral-300);
      border-radius: 8px;
      background: var(--neutral-50);
      
      .user-info {
        flex: 1;
        
        h4 {
          font-size: 16px;
          font-weight: 600;
          color: var(--neutral-700);
          margin-bottom: 4px;
        }
        
        p {
          font-size: 13px;
          color: var(--neutral-500);
          margin: 2px 0;
        }
      }
    }
  }
  
  .search-error {
    margin-top: 16px;
  }
}

@media (max-width: 768px) {
  .groups-grid {
    grid-template-columns: 1fr;
  }
  
  .search-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .search-left {
      flex-direction: column;
      
      .el-input,
      .el-select {
        width: 100%;
      }
    }
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>